package com.mini.service;

import com.mini.conditon.AppendRangeInfoCondition;
import com.mini.conditon.GroupManagerCondition;
import com.mini.constant.GroupOperatorTypeEnum;
import com.mini.model.*;
import com.mini.repository.BusinessRequirementPlanNeedRepository;
import com.mini.req.RequirementPlanFormReq;
import com.mini.req.RequirementPlanTableReq;
import com.mini.util.CalendarUtil;
import com.mini.vo.DeptVO;
import com.mini.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务模块内部操作记录保存服务
 *      操作记录根据内容不同各自业务模块自己实现
 *
 * @author: zhaocg
 * @created: 2021/01/20 14:22
 */
@Slf4j
@Service
public class InnerOperationRecordService extends BaseService {


    private static final String SYSTEM = "system";

    private static final long SYSTEM_ID = 0L;

    private static final int OPERATION_SOURCE_SYSTEM = 0;

    private static final int OPERATION_SOURCE_TEACHER = 1;

    @Autowired
    private BusinessOperationRecordService operationRecordService;

    @Autowired
    private MiniAdminService miniAdminService;

    @Autowired
    private DictionariesBaseService dictionariesBaseService;


    /**
     * 创建业务组
     *
     * @param condition
     * @param businessId
     */
    public void createBusinessGroup(GroupManagerCondition condition, Long businessId, String token) {
        try {
            StringBuffer sb = new StringBuffer();
            UserVO userVO = miniAdminService.getUserSimpleInfo(condition.getOperatorId());
            sb.append(CalendarUtil.getShortHHmmDateString(new Date()))
                    .append(Objects.nonNull(userVO) ? userVO.getUsername() : "")
                    .append(GroupOperatorTypeEnum.CREATE.getDesc())
                    .append(condition.getGroupName()).append("(").append(businessId).append(")的");

            if (!CollectionUtils.isEmpty(condition.getChannelCodeList()) ||
                    !CollectionUtils.isEmpty(condition.getProjectIdList()) ||
                    !CollectionUtils.isEmpty(condition.getRegionCodeList())) {
                sb.append("业务范围/所属销售组-【");
            }
            if (!CollectionUtils.isEmpty(condition.getProjectIdList())) {
                appendItemListName(sb, condition.getProjectIdList(), token);
            }
            if (!CollectionUtils.isEmpty(condition.getChannelCodeList())) {
                appendChannelListName(sb, condition.getChannelCodeList(), token);
            }
            if (!CollectionUtils.isEmpty(condition.getRegionCodeList())) {
                appendMapProvinceName(sb, condition.getRegionCodeList());
            }
            sb.append("】/【");
            if (!CollectionUtils.isEmpty(condition.getDeptIdList())) {
                appendDeptName(sb, condition.getDeptIdList());
            }
            operationRecordService.save(null , "" ,
                    OPERATION_SOURCE_TEACHER,sb.toString(),condition.getOperatorId(),
                    userVO.getNickname(),2,userVO.getUsername() , userVO.getRoleName(),new Date());
        } catch (Exception e) {
            log.error("createBusinessGroup error={}", e);
        }
    }

    /**
     * 变更销售组
     *
     * @param oldDeptIds
     * @param newDeptIds
     * @param businessId
     * @param userId
     * @param groupName
     */
    public void addBelongingInfo(List<Long> oldDeptIds, List<Long> newDeptIds, Long businessId,
                                 Long userId, String groupName) {
        try {
            StringBuffer sb = new StringBuffer();
            UserVO userVO = miniAdminService.getUserSimpleInfo(userId);
            sb.append(CalendarUtil.getShortHHmmDateString(new Date()))
                    .append(Objects.nonNull(userVO) ? userVO.getUsername() : "")
                    .append(groupName).append("(").append(businessId).append(")由原来所属销售组-");
            if (!CollectionUtils.isEmpty(oldDeptIds)) {
                appendDeptName(sb, oldDeptIds);
            }
            sb.append(GroupOperatorTypeEnum.MODIFY.getDesc()).append("为");
            if (!CollectionUtils.isEmpty(newDeptIds)) {
                appendDeptName(sb, newDeptIds);
            }
            operationRecordService.save(null, "",
                    OPERATION_SOURCE_TEACHER, sb.toString(), userId,
                    userVO.getNickname(), 2, userVO.getUsername(), userVO.getRoleName(), new Date());
        } catch (Exception e) {
            log.error("addBelongingInfo error={}" , e);
        }
    }

    /**
     * 删除业务范围
     */
    public void deletedRangingInfo(List<BusinessRangeInfo> businessRangeInfoList ,Long businessId,
                                   String token,String groupName){
        try {
            StringBuffer sb = new StringBuffer();
            UserVO userVO = miniAdminService.getLoginUser(token);
            sb.append(CalendarUtil.getShortHHmmDateString(new Date()))
                    .append(Objects.nonNull(userVO) ? userVO.getUsername() : "")
                    .append(GroupOperatorTypeEnum.DELETED.getDesc())
                    .append(groupName).append("(").append(businessId).append(")的业务范围-");
            if (businessRangeInfoList.size() > 1) {
                businessRangeInfoList.stream().forEach(rangeInfo -> {
                    sb.append("【")
                            .append(rangeInfo.getProjectName()).append("/")
                            .append(rangeInfo.getChannelName()).append("/")
                            .append(rangeInfo.getRegionName()).append("】");
                });
            } else {
                BusinessRangeInfo rangeInfo = businessRangeInfoList.get(0);
                sb.append("【")
                        .append(rangeInfo.getProjectName()).append("/")
                        .append(rangeInfo.getChannelName()).append("/")
                        .append(rangeInfo.getRegionName()).append("】");
            }
            operationRecordService.save(null, "",
                    OPERATION_SOURCE_TEACHER, sb.toString(), userVO.getId(),
                    userVO.getNickname(), 2, userVO.getUsername(), userVO.getRoleName(), new Date());
        } catch (Exception e) {
            log.error("deletedRangingInfo error={}" , e);
        }
    }

    /**
     * 追加业务范围
     */
    public void addRangingInfo(AppendRangeInfoCondition condition ,String token,String groupName){
        try {
            StringBuffer sb = new StringBuffer();
            UserVO userVO = miniAdminService.getLoginUser(token);
            sb.append(CalendarUtil.getShortHHmmDateString(new Date()))
                    .append(Objects.nonNull(userVO) ? userVO.getUsername() : "")
                    .append(GroupOperatorTypeEnum.APPEND.getDesc())
                    .append(groupName).append("(").append(condition.getBusinessGroupId()).append(")的业务范围-【");
            appendItemListName(sb, condition.getProjectIdList(), token);
            appendChannelListName(sb, condition.getChannelCodeList(), token);
            appendMapProvinceName(sb, condition.getRegionCodeList());
            sb.append("】");
            operationRecordService.save(null, "",
                    OPERATION_SOURCE_TEACHER, sb.toString(), userVO.getId(),
                    userVO.getNickname(), 2, userVO.getUsername(), userVO.getRoleName(), new Date());
        } catch (Exception e) {
            log.error("deletedRangingInfo error={}" , e);
        }
    }

    /**
     * 删除业务组
     *
     * @param token
     * @param businessId
     * @param businessGroupName
     */
    public void deletedBusinessGroup(String token ,Long businessId ,String businessGroupName){
        try {
            StringBuffer sb = new StringBuffer();
            UserVO userVO = miniAdminService.getLoginUser(token);
            sb.append(CalendarUtil.getShortHHmmDateString(new Date()))
                    .append(Objects.nonNull(userVO) ? userVO.getUsername() : "")
                    .append(GroupOperatorTypeEnum.DELETED.getDesc())
                    .append(businessGroupName).append("(").append(businessId).append(")");
            operationRecordService.save(null, "",
                    OPERATION_SOURCE_TEACHER, sb.toString(), userVO.getId(),
                    userVO.getNickname(), 2, userVO.getUsername(), userVO.getRoleName(), new Date());
        } catch (Exception e) {
            log.error("deletedBusinessGroup error={}" , e);
        }
    }

    /**
     * 拼接销售组
     *
     * @param deptIds
     */
    private void appendDeptName(StringBuffer sb , List<Long> deptIds){
        Set<Long> deptIdSet = new HashSet<>(deptIds);
        List<DeptVO> deptVOList = miniAdminService.getDeptsBatch(deptIdSet);
        List<String> deptNames = new ArrayList<>();
        if (!CollectionUtils.isEmpty(deptVOList)) {
            for (DeptVO deptVO : deptVOList) {
                deptNames.add(deptVO.getName() + "(" + deptVO.getId() + ")");
            }
        }
        String deptNameStrList = String.join(",", deptNames);
        sb.append(deptNameStrList).append("】");
    }

    /**
     * 拼接渠道名称
     *
     * @param sb
     * @param channelCodeList
     * @param token
     */
    private void appendChannelListName(StringBuffer sb , List<String> channelCodeList , String token){
        if (!CollectionUtils.isEmpty(channelCodeList)) {
            Map<String, String> channelCodeMap = dictionariesBaseService.getMapChannelInfo(token);
            List<String> channelList = new ArrayList<>();
            channelCodeList.stream().forEach(channelCode -> {
                channelList.add(channelCodeMap.get(channelCode));
            });
            String channelNames = String.join(",", channelList);
            sb.append("/").append(channelNames);
        }
    }

    /**
     * 拼接项目名称
     *
     * @param sb
     * @param projectList
     * @param token
     */
    private void appendItemListName(StringBuffer sb , List<Long> projectList , String token){
        if (!CollectionUtils.isEmpty(projectList)) {
            Map<Integer ,String> itemMaps = dictionariesBaseService.getMapItemInfo(token);
            List<String> projectNameList = new ArrayList<>();
            projectList.stream().forEach(projectId -> {
                projectNameList.add(itemMaps.get(Integer.valueOf(String.valueOf(projectId))));
            });
            String projectNames = String.join(",", projectNameList);
            sb.append("/").append(projectNames);
        }
    }

    /**
     * 拼接省份名称
     *
     * @param sb
     * @param provinceList
     */
    private void appendMapProvinceName(StringBuffer sb , List<String> provinceList){
        if (!CollectionUtils.isEmpty(provinceList)) {
            Map<String, String> provinceMap = dictionariesBaseService.getMapProvince();
            List<String> provinceNameList = new ArrayList<>();
            provinceList.stream().forEach(province -> {
                provinceNameList.add(provinceMap.get(province));
            });
            String provinceNames = String.join(",", provinceNameList);
            sb.append("/").append(provinceNames);
        }
    }

    /**
     * 最大接待量日志
     *
     * @param userId
     * @param log
     */
    public void addSetMaxLog(Long userId, String log) {
        StringBuffer sb = new StringBuffer();
        UserVO userVO = miniAdminService.getUserSimpleInfo(userId);
        operationRecordService.save(null, "",
                2, log, userId,
                userVO.getNickname(), 15, userVO.getUsername(), userVO.getRoleName(), new Date());
    }




}
